import { defineEventHandler, readBody } from 'h3'
import { getPool } from '../util/mysql'
import { recordLog } from '../util/log'

export default defineEventHandler(async (event: any) => {
  const body = await readBody(event).catch(() => ({}))
  const payment_no = body.payment_no ?? body.paymentNo ?? body.out_trade_no ?? null
  const payment_id = body.payment_id ?? body.paymentId ?? null
  // 支持多种 email 字段名
  const email = body.email ?? body.order_email ?? body.orderEmail ?? null

  if (!payment_no && !payment_id && !email) {
    event.node.res.statusCode = 400
    return { status: 400, message: 'missing payment_no, payment_id or email' }
  }

  try {
    const pool = await getPool()
    let rows: any = []

    // 优先按 payment_no 或 payment_id 查询，可同时提供 email 增加过滤精度
    if (payment_no || payment_id) {
      if (payment_no) {
        if (email) {
          const [r]: any = await pool.execute(
            `SELECT * FROM lin_order WHERE payment_no = ? AND email = ? `,
            [payment_no, email]
          )
          rows = r
          // 如果没有匹配到，同时尝试仅按 payment_no 回退（兼容旧数据）
          if ((!Array.isArray(rows) || rows.length === 0)) {
            const [r2]: any = await pool.execute(
              `SELECT * FROM lin_order WHERE payment_no = ?  `,
              [payment_no]
            )
            rows = r2
          }
        } else {
          const [r]: any = await pool.execute(
            `SELECT * FROM lin_order WHERE payment_no = ?  `,
            [payment_no]
          )
          rows = r
        }
      } else {
        // payment_id 查询，可加 email 过滤
        if (email) {
          const [r]: any = await pool.execute(
            `SELECT * FROM lin_order WHERE payment_id = ? AND email = ? `,
            [payment_id, email]
          )
          rows = r
          if ((!Array.isArray(rows) || rows.length === 0)) {
            const [r2]: any = await pool.execute(
              `SELECT * FROM lin_order WHERE payment_id = ?  `,
              [payment_id]
            )
            rows = r2
          }
        } else {
          const [r]: any = await pool.execute(
            `SELECT * FROM lin_order WHERE payment_id = ?  `,
            [payment_id]
          )
          rows = r
        }
      }
    } else if (email) {
      // 仅按 email 查询：返回最新一条订单（按 id 降序或可改为 created_at）
      const [r]: any = await pool.execute(
        `SELECT * FROM lin_order WHERE email = ?  ORDER BY id DESC `,
        [email]
      )
      rows = r
    }

    if (!Array.isArray(rows) || rows.length === 0) {
      return { status: 404, message: 'order not found' }
    }
    return { status: 200, data: rows }
  } catch (err: any) {
    event.node.res.statusCode = 500
    await recordLog(event, { message: `getorder error ${String(err?.message || err)}`, userId: 0 })
    return { status: 500, message: String(err?.message || err) }
  }
})
